<template>
    <div class="bg-box">
        <van-tabs v-model:active="active" @click-tab="handleTabs">
            <van-tab  title="账号密码">
                <div class="userbox1">
                    <van-form @submit="handleLogin">
                        <van-cell-group inset>

                            <van-field v-model="phone" name="phone" label="手机号" placeholder="请输入手机号"
                                :rules="[{ required: true, message: '请填写手机号' }]" />
                            <van-field type="password" v-model="password" name="password" label="密码" placeholder="请输入密码"
                                :rules="[{ required: true, message: '请填写密码' }]" />

                        </van-cell-group>
                        <van-button type="danger" native-type="submit" class="submit-btn">登录</van-button>


                    </van-form>
                </div>
            </van-tab>
            <van-tab title="验证码">
                <div class="userbox2">
                    <van-form @submit="handleCaptchaLogin">
                        <van-cell-group inset>
                            <van-field v-model="phone" name="phone" label="手机号" placeholder="请输入手机号"
                                :rules="[{ required: true, message: '请填写手机号' },{pattern:regxp,message:'手机号不正确'}]" />
                            <van-field center  v-model="captcha" name="captcha" label="验证码" placeholder="请输入验证码"
                                :rules="[{ required: true, message: '请填写验证码' }]">
                                <template #button>
                                    <van-button type="primary" @click="handleCaptcha" class="captcha-btn"
                                        :disabled="isCaptchaDisable" size="small">{{captchaText}}</van-button>
                                </template>
                            </van-field>
                        </van-cell-group>

                        <van-button type="primary" native-type="submit" class="submit-btn">登录</van-button>
                    </van-form>
                </div>
            </van-tab>
            <van-tab title="二维码">
                <div class="userbox3"><img :src="qrSrc" /></div>
            </van-tab>

        </van-tabs>
        <el-date-picker
      v-model="value2"
      type="daterange"
      @change="handleChange"
      placeholder="选择日期"
      format="YYYY/MM/DD"
      value-format="x"
      >
      
    </el-date-picker>
    </div>
</template>

<script lang="ts">import { defineComponent,reactive ,toRefs,onMounted} from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import {loginPassword} from "@/utils/api.js"
import { Toast } from "vant";
import { getUserDetail } from "@/utils/api.js"
import {getCaptcha,validateCaptcha,getQr,qrCreate,qrCheck} from "@/utils/api.js"
export default defineComponent({
setup() {
    const state=reactive({
        value2:0,
        active:0,
        phone:"",
        password:"",
        captcha:"",
        countT1:10,
        T1:null,
        T2:null,
        isCaptchaDisable:false,
        captchaText:"获取验证码",
        uniKey:"",
        qrSrc:"",
    })
    const store=useStore()
    const router=useRouter()
 const regxp = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
 const handleChange=(v)=>{
    console.log(v)
 }
    function handleLogin(value){
       async function login() {
            const response=await loginPassword(value)
            console.log(response)
            if(response.data.code===502){
                Toast.fail("手机号或密码错误")
                state.password=""
            }else if(response.data.code===200){
                
                const token=response.data.token
                sessionStorage.setItem("token",token)
                const id=response.data.account.id
                store.commit("changeUserId",id)
                async function getUser() {
                    const response = await getUserDetail({ uid: id })
                    console.log(response)
                    if(response.data.profile){
                        const userInfo=response.data.profile
                        sessionStorage.setItem("userInfo",JSON.stringify(userInfo))
                        store.commit("changeLogin", true)
                        router.push("/my")
                    }
                }
                
                getUser()
            }
        }
        login()
        

    }
   async function handleCaptcha(){
        if(state.phone.length==11){
            const response = await getCaptcha({ phone: state.phone })
            console.log("验证码请求返回", response)
            if(response.data.code==200){
                //定时器触发逻辑
                state.isCaptchaDisable=true
              state.T1=setInterval(()=>{
                    state.countT1=state.countT1-1
                    // console.log(state.countT1)
                    state.captchaText=state.countT1+"后重新获取验证码"
                    if(state.countT1==0){
                        clearInterval(state.T1)
                        state.isCaptchaDisable=false
                        state.captchaText ="重新获取验证码"
                        state.countT1=10
                    }
                },1000)
            }
        }else{
            Toast.fail("手机号不正确")
        }
        
    }
    function handleCaptchaLogin(value){
        async function captchaLogin(){
            const response= await validateCaptcha(value)
            console.log("验证码验证请求返回",response)
            if(response.data.code===200){
                const response2=await loginPassword(value)
                console.log("验证码登陆成功返回",response2)
                if (response.data.code === 502) {
                    Toast.fail("手机号或验证码错误")
                   
                } else if (response.data.code === 200) {

                    const token = response.data.token
                    sessionStorage.setItem("token", token)
                    const id = response.data.account.id
                    store.commit("changeUserId", id)
                    async function getUser() {
                        const response = await getUserDetail({ uid: id })
                        console.log(response)
                        if (response.data.profile) {
                            const userInfo = response.data.profile
                            sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
                            store.commit("changeLogin", true)
                            router.push("/my")
                        }
                    }

                    getUser()
                }
            }
        }
        captchaLogin()
    }
    function handleTabs({title}){
        if(title=="二维码"){
            async function getPrKey(){
                const response=await getQr()
                console.log("二维码key返回",response)
                if(response.data.code==200){
                    state.uniKey=response.data.data.unikey
                    console.log(state.uniKey)
                    const response2=await qrCreate({key:state.uniKey,qrimg:true})
                    console.log("二维码生成返回",response2)
                    if(response2.data.code==200){
                        state.qrSrc=response2.data.data.qrimg
                        state.T2=setInterval(()=>{
                           async function lunxun(){
                            const response3=await qrCheck({key:state.uniKey})
                            console.log("二维码状态轮询返回",response3)
                            //这里无法授权成功，轮询始终返回801？？？
                            if(response3.data.code==803){
                                clearInterval(state.T2)
                            }
                           }
                           lunxun()

                        },1000)
                    }
                }
            }
            
            getPrKey()
        }
        
    }
    
return {
    ...toRefs(state),
    handleLogin,
    handleCaptcha,
    handleCaptchaLogin,
    regxp,
    handleTabs,
    handleChange
};
},
});
</script>

<style lang="less" scoped>



.bg-box{
    width: 95%;
    margin: 0.2rem;
    height: 95%;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    .userbox1{
        .captcha-btn{
            position: absolute;
        }
        .submit-btn {
           
                width: 95%;
                position: absolute;
                right: 0.2rem;
                border-radius:0.4rem ;
            }

    }
    .van-tabs{
        width:100%;
    }
    .userbox2{
        .submit-btn {
                width: 95%;
                position: absolute;
                right: 0.2rem;
                border-radius: 0.4rem;
            }
       
    }   
    .userbox3{
        
        display: flex;
        align-items: center;   
        justify-content: center;
        img{
            widows: 3rem;
            height: 3rem;
        }
         }
    
}
</style>